<template>
	<view class="container">
		<w-head :title="'头像制作'"></w-head>
		<view class="avatar-container" @touchstart="touchStart" @touchend="touchEnd" @touchmove="touchMove">
			<view class="avatar-bg-border"><image @touchstart="touchAvatarBg" class="avatar-bg" id="avatar-bg" :src="avatarPath"></image></view>
			<image
				v-if="currentMaskId > -1"
				class="mask"
				:class="{ 'mask-with-border': showBorder }"
				id="mask"
				:src="maskPic"
				:style="{
					top: maskCenterY - maskSize / 2 - 2 + 'px',
					left: maskCenterX - maskSize / 2 - 2 + 'px',
					transform: 'rotate(' + rotate + 'deg)' + 'scale(' + scale + ')' + 'rotateY(' + rotateY + 'deg)'
				}"
			></image>
			<view class="handle" :class="{ 'hide-handle': !showBorder }" :style="{ top: handleCenterY - 10 + 'px', left: handleCenterX - 10 + 'px' }">
				<image class="handle-img" id="handle" src="/static/image/drag.svg"></image>
			</view>
			<view class="action-wrapper">
				<view class="action"><button class="cu-btn round shadow-blur bg-green" open-type="getUserInfo" @getuserinfo="getUserInfo">我的头像</button></view>
				<view class="action"><button class="cu-btn round shadow-blur bg-red" @click="draw">保存头像</button></view>
				<view class="action"><button class="cu-btn round  shadow-blur bg-orange" open-type="share">分享朋友</button></view>
			</view>
		</view>
		<view class="cans"><canvas class="cans-id-mask" canvas-id="cans-id-mask" /></view>
		<!-- <view class="ad-wraper">
			<ad unit-id="广告id"></ad>
		</view> -->
		<view class="ornaments-tabs">
			<scroll-view class="ornaments-scroll-view" scroll-x="true" :scroll-left="scrollLeft" @scroll="scroll">
				<view class="img-wrap" v-for="index in imgLength" :key="index">
					<image class="img-list" :src="`/static/image/${type}/${index}.png`" :data-mask-id="index" @tap="changeMask"></image>
				</view>
			</scroll-view>
		</view>
		<view class="type-tabs">
			<view class="left"><image class="left-img" src="/static/image/left.png"></image></view>
			<scroll-view class="type-tabs-scroll" scroll-x="true" scroll-with-animation="true">
				<block v-for="item in tabList" :Key="item.id">
					<button class="tab round shadow-blur bg-white" @click="changeType(item.click)">{{ item.name }}</button>
				</block>
			</scroll-view>
			<view class="right"><image class="right-img" src="/static/image/right.png"></image></view>
		</view>
	</view>
</template>
<script>
const getAvatar = path => {
	return `/static/image/${path}/avatar_mask.png`;
};
let interstitialAd = null;

import WHead from './head.vue';
export default {
	components:{
		WHead
	},
	data() {
		return {
			cansWidth: 280, // 宽度 px
			cansHeight: 280, // 高度 px
			avatarPath: getAvatar('newyear'),
			imgLength: 6,
			currentMaskId: -1,
			showBorder: false,
			maskCenterX: wx.getSystemInfoSync().windowWidth / 2,
			maskCenterY: 250,
			cancelCenterX: wx.getSystemInfoSync().windowWidth / 2 - 50 - 2,
			cancelCenterY: 200,
			handleCenterX: wx.getSystemInfoSync().windowWidth / 2 + 50 - 2,
			handleCenterY: 300,
			maskSize: 100,
			scale: 1,
			rotate: 0,
			rotateY: 0,
			mask_center_x: wx.getSystemInfoSync().windowWidth / 2,
			mask_center_y: 250,
			cancel_center_x: wx.getSystemInfoSync().windowWidth / 2 - 50 - 2,
			cancel_center_y: 200,
			handle_center_x: wx.getSystemInfoSync().windowWidth / 2 + 50 - 2,
			handle_center_y: 300,
			scaleCurrent: 1,
			rotateCurrent: 0,
			touch_target: '',
			start_x: 0,
			start_y: 0,
			shareObj: {
				title: '欢乐中国年，饰品来曾颜',
				imageUrl: getAvatar('newyear')
			},
			isAdShow: false,
			type: 'newyear',
			isSetAvatar: false,
			scrollLeft: 0,
			old: {
				scrollLeft: 0
			},
			tabList: [
				{
					click: 'newyear',
					name: '中国年',
					id: 1
				},
				{
					click: 'china',
					name: '红旗飘飘',
					id: 2
				},
				{
					click: 'mask',
					name: '口罩',
					id: 3
				},
				{
					click: 'christmas',
					name: '圣诞帽',
					id: 4
				}
			],
			colorList: [
				{
					title: '嫣红',
					name: 'red',
					color: '#e54d42'
				},
				{
					title: '桔橙',
					name: 'orange',
					color: '#f37b1d'
				},
				{
					title: '明黄',
					name: 'yellow',
					color: '#fbbd08'
				},
				{
					title: '橄榄',
					name: 'olive',
					color: '#8dc63f'
				},
				{
					title: '森绿',
					name: 'green',
					color: '#39b54a'
				},
				{
					title: '天青',
					name: 'cyan',
					color: '#1cbbb4'
				},
				{
					title: '海蓝',
					name: 'blue',
					color: '#0081ff'
				},
				{
					title: '姹紫',
					name: 'purple',
					color: '#6739b6'
				},
				{
					title: '木槿',
					name: 'mauve',
					color: '#9c26b0'
				},
				{
					title: '桃粉',
					name: 'pink',
					color: '#e03997'
				},
				{
					title: '棕褐',
					name: 'brown',
					color: '#a5673f'
				},
				{
					title: '玄灰',
					name: 'grey',
					color: '#8799a3'
				},
				{
					title: '草灰',
					name: 'gray',
					color: '#aaaaaa'
				},
				{
					title: '墨黑',
					name: 'black',
					color: '#333333'
				},
				{
					title: '雅白',
					name: 'white',
					color: '#ffffff'
				}
			]
		};
	},
	onLoad(option) {
		// #ifdef MP-WEIXIN
		// wx.showShareMenu({
		// 	menus: ["shareAppMessage", "shareTimeline"],
		// 	success(res) {},
		// 	fail(e) {},
		// })
		// if (wx.createInterstitialAd) {
		// 	interstitialAd = wx.createInterstitialAd({
		// 		adUnitId: "广告id",
		// 	})
		// 	interstitialAd.onLoad(() => {})
		// 	interstitialAd.onError((err) => {})
		// 	interstitialAd.onClose(() => {})
		// }
		// #endif
	},
	onShareAppMessage() {
		return {
			...this.shareObj,
			path: '/pages/cow/index',
			success: function(res) {}
		};
	},
	onShareTimeline(res) {
		return {
			...this.shareObj,
			query: ''
		};
	},
	methods: {
		// 选择图片
		chooseImage() {
			let that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: function(res) {
					that.avatarPath = res.tempFilePaths[0];
					that.isSetAvatar = true;
				}
			});
		},
		// 获取用户信息
		getUserInfo(result) {
			let that = this;
			if (result.detail.errMsg !== 'getUserInfo:ok') {
				uni.showModal({
					title: '获取用户头像失败',
					content: '亲，需要您授权访问头像才能给您的头像佩戴饰品哦',
					showCancel: false
				});
				return;
			}

			let userInfo = result.detail.userInfo;
			uni.showLoading({
				title: '获取中',
				mask: true
			});
			userInfo.avatarUrl = userInfo.avatarUrl.replace('132', '0').replace('https://thirdwx.qlogo.cn', 'https://wx.qlogo.cn'); // 使用最大分辨率头像 959 * 959
			uni.downloadFile({
				url: userInfo.avatarUrl,
				success: function(res) {
					uni.hideLoading();
					that.avatarPath = res.tempFilePath;
					that.isSetAvatar = true;
				},
				fail: function(e) {
					uni.hideLoading();
					uni.showToast({
						title: '图片加载超时',
						content: '网络异常，请稍后重试'
					});
				}
			});
		},
		scroll: function(e) {
			this.old.scrollLeft = e.detail.scrollLeft;
		},
		// 更换类型
		changeType(val) {
			if (this.type == val) {
				return;
			}
			this.scrollLeft = this.old.scrollLeft;
			this.$nextTick(function() {
				this.scrollLeft = 0;
			});
			this.currentMaskId = -1;
			this.showBorder = false;
			this.type = val;
			this.shareObj = { ...this.shareObj, imageUrl: getAvatar(val) };
			if (!this.isSetAvatar) {
				this.avatarPath = getAvatar(val);
			}
			if (val == 'christmas') {
				this.imgLength = 13;
				this.shareObj = { ...this.shareObj, title: '圣诞到，送你一顶圣诞帽' };
			} else if (val == 'newyear') {
				this.imgLength = 17;
				this.shareObj = { ...this.shareObj, title: '欢乐中国年，饰品来曾颜' };
			} else if (val == 'china') {
				this.imgLength = 9;
				this.shareObj = { ...this.shareObj, title: '献礼国庆，为祖国母亲庆生' };
			} else if (val == 'mask') {
				this.imgLength = 28;
				this.shareObj = { ...this.shareObj, title: '抗击疫情，人人有责' };
			}
		},
		// 选择挂件
		changeMask(e) {
			if (!this.isAdShow) {
				this.isAdShow = true;
				// interstitialAd.show().catch((err) => {
				// 	console.error(err)
				// })
			}
			this.currentMaskId = e.target.dataset.maskId;
			this.showBorder = true;
		},
		// 设置挂件位置
		touchStart(e) {
			if (e.target.id == 'mask') {
				this.touch_target = 'mask';
				this.showBorder = true;
			} else if (e.target.id == 'handle') {
				this.touch_target = 'handle';
			} else {
				this.touch_target = '';
			}

			if (this.touch_target != '') {
				this.start_x = e.touches[0].clientX;
				this.start_y = e.touches[0].clientY;
			}
		},
		touchMove(e) {
			var current_x = e.touches[0].clientX;
			var current_y = e.touches[0].clientY;
			var moved_x = current_x - this.start_x;
			var moved_y = current_y - this.start_y;
			if (this.touch_target == 'mask') {
				this.maskCenterX = this.maskCenterX + moved_x;
				this.maskCenterY = this.maskCenterY + moved_y;
				this.cancelCenterX = this.cancelCenterX + moved_x;
				this.cancelCenterY = this.cancelCenterY + moved_y;
				this.handleCenterX = this.handleCenterX + moved_x;
				this.handleCenterY = this.handleCenterY + moved_y;
			}
			if (this.touch_target == 'handle') {
				this.handleCenterX = this.handleCenterX + moved_x;
				this.handleCenterY = this.handleCenterY + moved_y;
				this.cancelCenterX = 2 * this.maskCenterX - this.handleCenterX;
				this.cancelCenterY = 2 * this.maskCenterY - this.handleCenterY;
				let diff_x_before = this.handle_center_x - this.mask_center_x;
				let diff_y_before = this.handle_center_y - this.mask_center_y;
				let diff_x_after = this.handleCenterX - this.mask_center_x;
				let diff_y_after = this.handleCenterY - this.mask_center_y;
				let distance_before = Math.sqrt(diff_x_before * diff_x_before + diff_y_before * diff_y_before);
				let distance_after = Math.sqrt(diff_x_after * diff_x_after + diff_y_after * diff_y_after);
				let angle_before = (Math.atan2(diff_y_before, diff_x_before) / Math.PI) * 180;
				let angle_after = (Math.atan2(diff_y_after, diff_x_after) / Math.PI) * 180;
				this.scale = (distance_after / distance_before) * this.scaleCurrent;
				this.rotate = angle_after - angle_before + this.rotateCurrent;
			}
			this.start_x = current_x;
			this.start_y = current_y;
		},
		touchEnd(e) {
			this.mask_center_x = this.maskCenterX;
			this.mask_center_y = this.maskCenterY;
			this.cancel_center_x = this.cancelCenterX;
			this.cancel_center_y = this.cancelCenterY;
			this.handle_center_x = this.handleCenterX;
			this.handle_center_y = this.handleCenterY;
			this.touch_target = '';
			this.scaleCurrent = this.scale;
			this.rotateCurrent = this.rotate;
		},
		// 不显示border
		touchAvatarBg() {
			this.showBorder = false;
		},
		// 绘制头像
		draw() {
			if (this.currentMaskId == -1) {
				uni.showToast({
					title: '您还没选择挂件哦',
					duration: 2000,
					icon: 'none'
				});
				return;
			}
			let scale = this.scale;
			let rotate = this.rotate;
			let mask_center_x = this.mask_center_x;
			let mask_center_y = this.mask_center_y;
			let that = this;
			var query = wx.createSelectorQuery();
			query.select('#avatar-bg').boundingClientRect();
			query.exec(function(res) {
				mask_center_x = mask_center_x - res[0].left;
				mask_center_y = mask_center_y - res[0].top;
				const context = wx.createCanvasContext('cans-id-mask');
				const mask_size = 100 * scale;
				context.clearRect(0, 0, that.cansWidth, that.cansHeight);
				context.drawImage(that.avatarPath, 0, 0, that.cansWidth, that.cansHeight);
				context.translate(mask_center_x, mask_center_y);
				context.rotate((rotate * Math.PI) / 180);
				context.drawImage(that.maskPic, -mask_size / 2, -mask_size / 2, mask_size, mask_size);
				context.draw(false, () => {
					that.saveCans();
				});
			});
		},
		// 保存头像
		saveCans() {
			let that = this;
			uni.showLoading({
				title: '保存...',
				mask: true
			});
			uni.canvasToTempFilePath(
				{
					x: 0,
					y: 0,
					height: this.cansWidth,
					width: this.cansHeight,
					destWidth: this.cansWidth * 3,
					destHeight: this.cansHeight * 3,
					canvasId: 'cans-id-mask',
					success: function(res) {
						uni.hideLoading();
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: function(res) {
								uni.showModal({
									title: '保存成功',
									content: '头像已经在您的相册里啦',
									showCancel: false
								});
							},
							fail(res) {
								if (res.errMsg.indexOf('fail')) {
									uni.showModal({
										title: '您需要授权相册权限',
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success(res) {},
													fail(res) {}
												});
											}
										}
									});
								}
							}
						});
					},
					fail(res) {
						uni.hideLoading();
					}
				},
				this
			);
		}
	},
	computed: {
		maskPic: function() {
			return `/static/image/${this.type}/${this.currentMaskId}.png`;
		}
	}
};
</script>

<style lang="scss">
.container {
	position: absolute;
	width: 750rpx;
	height: 100%;
	background-color: #c12928;
	overflow: hidden;
	.avatar-container {
		height: 720rpx;
		width: 650rpx;
		margin: 100rpx auto 0;
		background-color: #fff;
		border-radius: 12rpx;
		.avatar-bg-border {
			position: relative;
			width: 560rpx;
			height: 560rpx;
			margin: 30rpx auto;
			.avatar-bg {
				position: absolute;
				margin-top: 30rpx;
				z-index: 0;
				height: 560rpx;
				width: 560rpx;
			}
		}
		.mask-with-border {
			border: dashed 4rpx white !important;
		}
		.delete {
			position: absolute;
			z-index: 1;
			width: 50rpx;
			height: 50rpx;
			background: #fff;
			border-radius: 50%;
			font-size: 30rpx;
			color: #000;
			line-height: 50rpx;
			text-align: center;
		}
		.mask {
			height: 100px;
			width: 100px;
			position: absolute;
			top: 100px;
			border: 2rpx solid rgba(255, 255, 255, 0);
		}
		.handle {
			position: absolute;
			z-index: 1;
			width: 50rpx;
			height: 50rpx;
			background: #fff;
			border-radius: 50%;
			font-size: 30rpx;
			color: #000;
			line-height: 50rpx;
			text-align: center;
			.handle-img {
				margin: 2rpx auto;
				width: 46rpx;
				height: 46rpx;
				position: absolute;
				left: 0;
			}
		}
		.hide-handle {
			display: none;
		}
	}
	.cans {
		.cans-id-mask {
			position: absolute;
			top: 2000px;
			left: 1000px;
			height: 270px;
			width: 270px;
			margin-left: auto;
			margin-right: auto;
		}
	}
	.action-wrapper {
		height: 110rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		font-weight: 900;
	}
	.ad-wraper {
		margin: 0 auto;
		width: 700rpx;
		height: 100rpx;
	}
	.type-tabs {
		width: 100%;
		height: 140rpx;
		position: absolute;
		bottom: 60rpx;
		display: flex;
		.left {
			width: 40rpx;
			height: 80rpx;
			.left-img {
				width: 40rpx;
				height: 80rpx;
			}
		}
		.right {
			width: 40rpx;
			height: 80rpx;
			.right-img {
				width: 40rpx;
				height: 80rpx;
			}
		}
		.type-tabs-scroll {
			width: 670rpx;
			white-space: nowrap;
			.tab {
				width: 200rpx;
				height: 80rpx;
				text-align: center;
				line-height: 80rpx;
				color: #333;
				font-weight: 900;
				font-size: 30rpx;
				display: inline-block;
				margin: 0 20rpx;
			}
		}
	}
	.ornaments-tabs {
		width: 100%;
		display: flex;
		height: 270rpx;
		margin-top: 60rpx;
		.left {
			width: 40rpx;
			height: 170rpx;
			.left-img {
				width: 40rpx;
				height: 170rpx;
			}
		}
		.right {
			width: 40rpx;
			height: 170rpx;
			.right-img {
				width: 40rpx;
				height: 170rpx;
			}
		}
		.ornaments-scroll-view {
			white-space: nowrap;
			width: 750rpx;
			.img-wrap {
				display: inline-flex;
				.img-list {
					height: 130rpx;
					width: 130rpx;
					border: 4rpx solid white;
					border-radius: 10rpx;
					margin: 20rpx;
				}
			}
		}
	}
}
</style>
